
const redis = require('ioredis');
const redisClient = redis.createClient({ host: '106.13.233.100', port: '6379', username: '', password: '123456' });

redisClient.on('connect', () => {
    console.log('connected to redis successfully!');
})

redisClient.on('error', (error) => {
    console.log('Redis connection error :', error);
})

// 存储值
function set(key, val) {
    if (typeof val === 'object') {
        val = JSON.stringify(val)
    }
    redisClient.set(key, val, redis.print)
}

// 读取值
function get(key) {
    const promise = new Promise((resolve, reject) => {
        redisClient.get(key, (err, val) => {
            // 出错
            if (err) {
                console.log('', err)
                reject(err)
                return
            }
            console.log('=== ', val)
            // 值为空
            if (val == null) {
                resolve(null)
                return
            }
            // 如果是json则转为对象，否则直接返回设置的值
            try {
                resolve(JSON.parse(val))
            } catch (ex) {
                resolve(val)
            }
        })
    })
    return promise
}

// set('name', 'test');
get('name');

setTimeout(() => {
    // 关闭
    redisClient.end()
}, 2000);